package uglify;

import java.io.InputStreamReader;
import java.io.Reader;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class UglifyJS {

    public static void main(String[] args) throws ScriptException {

        new UglifyJS().exec(args);
    }

    public Reader getResourceReader(String url) {
        return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(url));
    }

    public void exec(String[] args) throws ScriptException {

        ScriptEngine engine = ECMAScriptEngineFactory.getECMAScriptEngine();
        engine.put("uglify_args", args);
        engine.put("uglify_no_output", false);
        run(engine);

        engine.eval("uglify();");
    }

    private void run(ScriptEngine engine) throws ScriptException {

        Reader parsejsReader = getResourceReader("uglify/javascript/parse-js.js");
        Reader processjsReader = getResourceReader("uglify/javascript/process.js");
        Reader sysjsReader = getResourceReader("uglify/javascript/adapter/sys.js");
        Reader jsonjsReader = getResourceReader("uglify/javascript/adapter/JSON.js");
        Reader arrayjsReader = getResourceReader("uglify/javascript/adapter/Array.js");
        Reader uglifyjsReader = getResourceReader("uglify/javascript/uglifyjs.js");

        engine.eval(arrayjsReader);
        engine.eval(sysjsReader);
        engine.eval(parsejsReader);
        engine.eval(processjsReader);
        engine.eval(jsonjsReader);
        engine.eval(uglifyjsReader);

    }

    public String uglify(String[] args) throws ScriptException {

        ScriptEngine engine = ECMAScriptEngineFactory.getECMAScriptEngine();
        engine.put("uglify_args", args);
        engine.put("uglify_no_output", true);
        run(engine);

        return (String) engine.eval("uglify();");

    }

}
